package com.xhsj.user.hr.system.service;

import com.xhsj.user.hr.process.hrLeaveProcess.entity.TbHrApprovalLeaveTime;
import com.xhsj.user.hr.process.hrLeaveProcess.mapper.TbHrApprovalLeaveTimeMapper;
import com.xhsj.user.hr.process.hrLeaveProcess.service.TbHrApprovalLeaveApplyService;
import com.xhsj.user.hr.system.entity.TbHrLeaveSetting;
import com.xhsj.user.hr.system.entity.TbHrLeaveUseNum;
import com.xhsj.user.hr.system.entity.TbHrUserSocialSecurity;
import com.xhsj.user.hr.system.mapper.TbHrLeaveHiUseNumMapper;
import com.xhsj.user.hr.system.mapper.TbHrLeaveUseNumMapper;
import com.xhsj.user.hr.system.mapper.TbHrUserSocialSecurityMapper;
import com.xhsj.user.hr.base.BaseService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xhsj.user.hr.system.vo.ConfirmSocialSecurityVo;
import com.xhsj.user.utils.DateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.Period;
import java.time.temporal.ChronoUnit;
import java.util.*;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import java.io.Serializable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import lombok.extern.slf4j.Slf4j;
/**
 * <p>
 * 用户社保凭证表 服务实现类
 * </p>
 *
 * @author suxiaolin
 * @since Aug 5, 2021 6:20:16 AM
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class TbHrUserSocialSecurityService extends BaseService<TbHrUserSocialSecurityMapper, TbHrUserSocialSecurity>{
    @Autowired
    private TbHrUserSocialSecurityMapper dao;

    @Autowired
    private TbHrApprovalLeaveApplyService tbHrApprovalLeaveApplyService;

    @Autowired
    private TbHrLeaveUseNumMapper tbHrLeaveUseNumMapper;
    @Autowired
    private TbHrLeaveSettingService tbHrLeaveSettingService;
    @Autowired
    private TbHrApprovalLeaveTimeMapper tbHrApprovalLeaveTimeMapper;
    @Autowired
    private TbHrLeaveHiUseNumMapper tbHrLeaveHiUseNumMapper;

    /**
     * 保存
     * @author suxiaolin
     * @date Aug 5, 2021 6:20:16 AM
     */
    @Override
    public boolean save(TbHrUserSocialSecurity entity) {
        return super.save(entity);
    }

    /**
     * 通过id获取数据
     * @author suxiaolin
     * @date Aug 5, 2021 6:20:16 AM
     */
    @Override
    public TbHrUserSocialSecurity getById(Serializable id) {
        return super.getById(id);
    }

    /**
     * 通过id删除数据
     * @author suxiaolin
     * @date Aug 5, 2021 6:20:16 AM
     */
    @Override
    public boolean removeById(Serializable id) {
        return super.removeById(id);
    }

    /**
     * 分页查询数据
     * @author suxiaolin
     * @date Aug 5, 2021 6:20:16 AM
     */
    public IPage<TbHrUserSocialSecurity> selectPage(Map<String,Object> data) {
        int currentPage=1;
        if (!Objects.isNull(data.get("page"))) {
            currentPage=(Integer) data.get("page");
        }
        int pageSize=20;
        if (!Objects.isNull(data.get("size"))) {
            pageSize=(Integer) data.get("size");
        }

        TbHrUserSocialSecurity entity = JSON.parseObject(JSON.toJSONString(data), TbHrUserSocialSecurity.class);
        Page<TbHrUserSocialSecurity> page = new Page(currentPage,pageSize);
        QueryWrapper<TbHrUserSocialSecurity> wrapper = new QueryWrapper(entity);
        return super.selectPage(page, wrapper);
    }

    /**
     * 查询所有数据
     * @author suxiaolin
     * @date Aug 5, 2021 6:20:16 AM
     */
    @Override
    public List<TbHrUserSocialSecurity> selectAll() {
        return super.selectAll();
    }


    /**
     * 获取用户社保凭证
     * @author 苏小林
     * @date 2021/8/6 9:41
     * @param: userId
     * @return: com.xhsj.user.hr.system.entity.TbHrUserSocialSecurity
     */
    public TbHrUserSocialSecurity getUserSocialSecurity(Long userId,Long dataId) throws Exception {
        // 获取年假过期时间
        QueryWrapper<TbHrLeaveSetting> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("del_flag",0);
        List<TbHrLeaveSetting> list = tbHrLeaveSettingService.list(queryWrapper1);
        String annualLeaveExpireDate = null;
        if(list != null){
            TbHrLeaveSetting tbHrLeaveSetting = list.get(0);
              annualLeaveExpireDate = tbHrLeaveSetting.getAnnualLeaveExpireDate();
        }

        TbHrUserSocialSecurity userSocialSecurity = dao.getUserSocialSecurity(userId);
        // 获取年假已休表
        if (userSocialSecurity != null) {
            LocalDate confirmDate = DateUtils.date2LocalDate(userSocialSecurity.getConfirmDate());
            if (confirmDate != null) {
                LocalDate currentDate = LocalDate.now();
                long months = confirmDate.until(currentDate, ChronoUnit.MONTHS);
                Integer workingYears = userSocialSecurity.getWorkingYears();
                Integer workingMonth = userSocialSecurity.getWorkingMonth();
                int y = (workingMonth + (int)months) / 12;
                int m = (workingMonth + (int)months) % 12;

                userSocialSecurity.setCurrentWorkingYears(workingYears+y);
                userSocialSecurity.setCurrentWorkingMonth(m);
                // 去年年假结余和已休
                QueryWrapper<TbHrLeaveUseNum> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("social_security_id",userSocialSecurity.getId());
                queryWrapper.eq("year",currentDate.getYear());
                TbHrLeaveUseNum tbHrLeaveUseNum = tbHrLeaveUseNumMapper.selectOne(queryWrapper);
                if(tbHrLeaveUseNum == null)
                    tbHrLeaveUseNum = new TbHrLeaveUseNum();
                userSocialSecurity.setUseNum(tbHrLeaveUseNum.getUseNum());
                String s = tbHrApprovalLeaveApplyService.availableAnnualLeave(userSocialSecurity, userId, dataId);
                String[] split = s.split("&");
                int available = Integer.parseInt(split[0]);
                int useNumber = Integer.parseInt(split[1]);
                userSocialSecurity.setTotalNumber(available<0?0:available);
                userSocialSecurity.setUseNumber(useNumber<0?0:useNumber);
                userSocialSecurity.setSurplusNum((available-useNumber)<0?0:(available-useNumber));
                if (tbHrLeaveUseNum != null) {
                    userSocialSecurity.setPreTotalNum(tbHrLeaveUseNum.getPreTotalNum()<0?0:tbHrLeaveUseNum.getPreTotalNum());
                    userSocialSecurity.setPreUseNum(tbHrLeaveUseNum.getPreUseNum()<0?0:tbHrLeaveUseNum.getPreUseNum());
                    userSocialSecurity.setPreSurplusNum((tbHrLeaveUseNum.getPreTotalNum() - tbHrLeaveUseNum.getPreUseNum())<0?0:tbHrLeaveUseNum.getPreTotalNum() - tbHrLeaveUseNum.getPreUseNum());
                }
                log.info("最新工龄："+(workingYears+y)+"年"+(m)+"月");
            }
            userSocialSecurity.setAnnualLeaveExpireDate(annualLeaveExpireDate);
        }

        return userSocialSecurity;
    }

    /**
     * 通过用户id修改数据
     * @author 苏小林
     * @date 2021/8/6 16:34
     * @param: tbHrUserSocialSecurity
     */
    public void updateByUserId(TbHrUserSocialSecurity tbHrUserSocialSecurity) {
        dao.updateByUserId(tbHrUserSocialSecurity);
    }

    public void delByUserId(Long proposerId) {
        dao.delByUserId(proposerId);
    }

    public void handleConfirmSocialSecurity(ConfirmSocialSecurityVo entity) throws Exception {
        TbHrUserSocialSecurity tbHrUserSocialSecurity = new TbHrUserSocialSecurity();
        BeanUtils.copyProperties(entity,tbHrUserSocialSecurity);
        tbHrUserSocialSecurity.setConfirmDate(new Date());
        int i = dao.updateById(tbHrUserSocialSecurity);
        if (i == 0) {
            throw new Exception("记录不存在");
        }
        // 去年年假数
        TbHrLeaveUseNum tbHrLeaveUseNum = tbHrApprovalLeaveApplyService.data(entity.getUserId(),tbHrUserSocialSecurity,1);
        // 删除
        tbHrLeaveUseNumMapper.deleteByData(tbHrLeaveUseNum.getYear(),tbHrLeaveUseNum.getSocialSecurityId());
        tbHrLeaveUseNum.setUseNum(entity.getUseNum());
        if (tbHrLeaveUseNumMapper.insert(tbHrLeaveUseNum) != 1) {
            throw new Exception("保存年假已休表异常");
        }

//        QueryWrapper<TbHrApprovalLeaveTime> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("data_id", entity.getDataId());
//        List<TbHrApprovalLeaveTime> tbHrApprovalLeaveTimes = tbHrApprovalLeaveTimeMapper.selectList(queryWrapper);
//        tbHrApprovalLeaveApplyService.checkTiem(tbHrApprovalLeaveTimes, tbHrUserSocialSecurity);
//        tbHrLeaveHiUseNumMapper.deleteByDataId(entity.getDataId());

    }

    public void updateUseNum(Long id, int sum) {
        dao.updateUseNum(id,sum);
    }
}
